using B.S.XZYData.Api.Read.Application.Command.SalesOrder;
using B.S.XZYData.Domain.XZY;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using SqlSugar;
using SalesOrderProductEntity = B.S.XZYData.Domain.XZY.SalesOrderProduct;

namespace B.S.XZYData.Api.Read.Application.Handler.SalesOrder
{
    /// <summary>
    /// 查询销售订单产品明细处理器
    /// </summary>
    public class QuerySalesOrderProductHandler : IRequestHandler<QuerySalesOrderProductCommand, ApiResult<ApiPageing<SalesOrderProductDTO>>>
    {
        private readonly IBaseRepository<SalesOrderProductEntity> _salesOrderProductRepo;

        public QuerySalesOrderProductHandler(IBaseRepository<SalesOrderProductEntity> salesOrderProductRepo)
        {
            _salesOrderProductRepo = salesOrderProductRepo;
        }

        public async Task<ApiResult<ApiPageing<SalesOrderProductDTO>>> Handle(QuerySalesOrderProductCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var query = _salesOrderProductRepo.GetAll()
                    .Where(x => x.SalesOrderId == request.SalesOrderId && !x.IsDeleted);

                // 按创建时间倒序
                query = query.OrderByDescending(x => x.CreateTime);

                // 分页查询
                var total = await query.CountAsync();
                var list = await query
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync();

                // 转换为DTO
                var dtoList = list.Select(x => new SalesOrderProductDTO
                {
                    Id = x.Id,
                    SalesOrderId = x.SalesOrderId,
                    ProductCode = x.ProductCode,
                    ProductName = x.ProductName,
                    ProductSpec = x.ProductSpec,
                    WorkOrderNo = x.WorkOrderNo,
                    Quantity = x.Quantity,
                    CompletedQuantity = x.CompletedQuantity,
                    CreateTime = x.CreateTime,
                    CreatorName = "超级管理员" // 这里应该根据CreatorId查询用户表获取用户名
                }).ToList();

                var result = new ApiPageing<SalesOrderProductDTO>
                {
                    TotaCount = total,
                    PageData = dtoList
                };

                return ApiResult<ApiPageing<SalesOrderProductDTO>>.Success(result);
            }
            catch (Exception ex)
            {
                return ApiResult<ApiPageing<SalesOrderProductDTO>>.Error($"查询销售订单产品明细失败：{ex.Message}");
            }
        }
    }
}
